package com.curator.component;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ReUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;

/**
 * redis 安装策略
 *
 * @author Jun
 * @date 2024/12/4
 */
public class ComponentInstallMaven extends AbstractComponentInstall {

    private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInstallMaven.class);

    @Override
    public String componentName() {
        return "Maven";
    }

    @Override
    public void componentInstall(InputStream inputStream, boolean runScript) {
        super.componentInstall(inputStream, true);
        try {
            String settingsXml = getFilePath(componentName(), "\\conf\\settings.xml");
            String xmlStr = FileUtil.readUtf8String(settingsXml);
            // 要替换的新内容
            String newContent = "<localRepository>" + getFilePath(componentName(), " Repository") + "</localRepository>";
            // 使用正则表达式替换 <localRepository></localRepository> 标签内的内容
            String modifiedText = ReUtil.replaceAll(xmlStr, "<localRepository>(.*?)</localRepository>", newContent);
            FileUtil.writeUtf8String(modifiedText, settingsXml);
            // 获取当前用户的主目录
            String userHome = System.getProperty("user.home");
            userHome += "\\.m2\\settings.xml";
            // 复制文件
            FileUtil.copy(settingsXml, userHome, true);
        } catch (Exception e) {
            LOGGER.error("{} 配置出现异常 {}", componentName(), ExceptionUtil.stacktraceToString(e));
        }
    }
}
